package servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Account;
import model.Connect;
import model.MyCrypto;
import model.SQLModel;



/**
 * Servlet implementation class ServletLogin
 */
public class ServletLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Connection conn;
	private HttpSession session;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletLogin() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		try{

			if (request.getMethod().equalsIgnoreCase("post")||request.getMethod().equalsIgnoreCase("get")) {
				try {
					myinit(request);
					PreparedStatement st = conn
							.prepareStatement("Select username,password,role from Account where username = ?");
					String role;
					MyCrypto crypto = new MyCrypto();
					String username= request.getParameter("txtUserName");
					String password= request.getParameter("txtPassword");
					st.setString(1, username);
					String encryptPass=crypto.encryptString(password, "DES","DES/ECB/PKCS5Padding");
					
					ResultSet rs = st.executeQuery();
					if (rs != null && rs.next()) {
							String password1= rs.getString(2);
							//String password1= new String(rs.getBytes(2));
							
							role =rs.getString(3);
							System.out.println(password1 +" ***** "+encryptPass );
							if(encryptPass.equals(password1)){
							
								Account acc = new Account(username,password,role);
								session = request.getSession(true);
								session.setMaxInactiveInterval(3600);
								session.setAttribute("acc",acc);
							
								
								if("admin_role".equalsIgnoreCase(role)){
									st.close();
									conn.close();
								
									response.sendRedirect("./UserManagement");
									//System.out.println("Hello Admin!");
								}
								else{
									
									st.close();
									conn.close();
									response.sendRedirect("./ViewItemTable?owner=admin");
									//System.out.println("Hello User!");
								}
							}
					}
					st.close();
					conn.close();
					response.sendRedirect("JSP/Login.jsp");
					System.out.println("Login Fail");
					
				} catch (Exception e) {
					System.out.print("Connection unsuccessfly "+ e.getMessage());
					//response.sendRedirect("ManageAccount/Login.jsp");
				}
			}

		}catch(Exception ex){
			System.out.println(ex.getMessage());
		}
	}
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request,response);
	}
	private void myinit(HttpServletRequest request )throws Exception{
		
		ServletConfig config = getServletConfig();
	    String SID = config.getInitParameter("SID");         
	    String user = config.getInitParameter("username");   
	    String pass = config.getInitParameter("password");   
		Connect connect = new Connect(SID,user,pass);
		//Connect connect = new Connect();
	   conn = connect.create_connect();	
		if(conn!=null){
			session = request.getSession(true);
			session.setMaxInactiveInterval(3600);
			session.setAttribute("SID",SID);
			session.setAttribute("passSYS",pass );
		}
		SQLModel db =new SQLModel(conn);
		
		PreparedStatement st = conn
				.prepareStatement("Select username from Account where username = ?");
		st.setString(1, "ADMIN");
		ResultSet rs =st.executeQuery();
		
		if(rs==null || !rs.next()){
			System.out.println("HERE");
			db.initUsers("ADMIN", "password","UNLIMITED","","ADMIN_ROLE");
			db.initUsers("SALER1", "password","UNLIMITED","SALER_PROFILE","SALER_ROLE");
			db.initUsers("SALER2", "password","UNLIMITED","SALER_PROFILE","SALER_ROLE");
			db.initUsers("SALER3", "password","UNLIMITED","SALER_PROFILE","SALER_ROLE");
		}
		st.close();
		
	}

}
